from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData
from django.conf import settings
from meiduo import constants
from meiduo.models import Users
import logging


# 定义日志输出器
logger = logging.getLogger("django")

def check_verify_email_token(token):
    """
    反序列化邮箱
    :param token: 　用户信息
    :return:    用户
    """
    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data = s.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get("user_id")
        email = data.get("email")
        try:
            user = Users.objects.get(id=user_id, email=email)
        except Users.DoesNotExist:
            return None
        else:
            return user



def generate_verify_email_url(user):
    """商城邮件激活连接"""

    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {"user_id": user.id, "email": user.email}
    token = s.dumps(data)

    return settings.EMAIL_VERIFY_URL + '?token=' + token.decode()